<template>
  <div class="performance-page">
    <h2>我的业绩</h2>

    <!-- 日期选择 -->
    <div class="date-selector">
      <el-radio-group v-model="dateRange" @change="handleDateRangeChange">
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="custom">自定义</el-radio-button>
      </el-radio-group>
      
      <el-date-picker
        v-if="dateRange === 'custom'"
        v-model="customDates"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        @change="loadPerformance"
        style="margin-left: 20px"
      />
    </div>

    <!-- 统计卡片 -->
    <div v-loading="loading" class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card orders">
            <div class="stat-icon">
              <el-icon :size="40"><Tickets /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ performance.totalOrders || 0 }}</div>
              <div class="stat-label">处理订单数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card sales">
            <div class="stat-icon">
              <el-icon :size="40"><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ performance.totalSales || 0 }}</div>
              <div class="stat-label">总销售额</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card refunds">
            <div class="stat-icon">
              <el-icon :size="40"><RefreshLeft /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ performance.totalRefunds || 0 }}</div>
              <div class="stat-label">退款金额</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card net-sales">
            <div class="stat-icon">
              <el-icon :size="40"><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ performance.totalNetSales || 0 }}</div>
              <div class="stat-label">净销售额</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 业绩趋势图 -->
    <el-card v-if="performance.trend && performance.trend.length > 0" class="trend-card">
      <template #header>
        <div class="card-header">
          <span>业绩趋势</span>
        </div>
      </template>
      <div id="trendChart" style="width: 100%; height: 400px;"></div>
    </el-card>

    <!-- 无数据提示 -->
    <el-empty v-if="!loading && !performance.totalOrders" description="暂无业绩数据" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getMyPerformance } from '@/api/performance'
import * as echarts from 'echarts'

const loading = ref(false)
const dateRange = ref('month')
const customDates = ref([])
const performance = reactive({
  totalOrders: 0,
  totalSales: 0,
  totalRefunds: 0,
  totalNetSales: 0,
  trend: []
})

let chartInstance = null

// 加载业绩数据
const loadPerformance = async () => {
  loading.value = true
  try {
    let params = {}
    
    if (dateRange.value === 'custom' && customDates.value && customDates.value.length === 2) {
      params = {
        startDate: customDates.value[0],
        endDate: customDates.value[1]
      }
    } else if (dateRange.value === 'month') {
      // 本月数据，后端会自动计算
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      params = {
        startDate: `${year}-${month}-01`,
        endDate: `${year}-${month}-${day}`
      }
    }
    
    const res = await getMyPerformance(params)
    if (res.code === 200) {
      Object.assign(performance, res.data)
      
      // 渲染图表
      if (performance.trend && performance.trend.length > 0) {
        await nextTick()
        renderChart()
      }
    } else {
      ElMessage.error(res.message || '加载业绩数据失败')
    }
  } catch (error) {
    console.error('加载业绩数据失败', error)
    ElMessage.error('加载业绩数据失败')
  } finally {
    loading.value = false
  }
}

// 日期范围变化
const handleDateRangeChange = () => {
  if (dateRange.value === 'month') {
    customDates.value = []
    loadPerformance()
  }
}

// 渲染图表
const renderChart = () => {
  const chartDom = document.getElementById('trendChart')
  if (!chartDom) return
  
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(chartDom)
  
  const dates = performance.trend.map(item => item.date)
  const salesData = performance.trend.map(item => item.salesAmount || 0)
  const refundData = performance.trend.map(item => item.refundAmount || 0)
  const netSalesData = performance.trend.map(item => item.netSales || 0)
  const orderData = performance.trend.map(item => item.orderCount || 0)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['销售额', '退款金额', '净销售额', '订单数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: [
      {
        type: 'value',
        name: '金额（元）',
        position: 'left'
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        data: salesData,
        smooth: true,
        itemStyle: {
          color: '#67c23a'
        }
      },
      {
        name: '退款金额',
        type: 'line',
        data: refundData,
        smooth: true,
        itemStyle: {
          color: '#f56c6c'
        }
      },
      {
        name: '净销售额',
        type: 'line',
        data: netSalesData,
        smooth: true,
        itemStyle: {
          color: '#409eff'
        }
      },
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 1,
        data: orderData,
        smooth: true,
        itemStyle: {
          color: '#e6a23c'
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
  
  // 窗口大小改变时重新渲染
  window.addEventListener('resize', () => {
    chartInstance && chartInstance.resize()
  })
}

onMounted(() => {
  loadPerformance()
})
</script>

<style scoped lang="scss">
.performance-page {
  padding: 20px;

  h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
  }

  .date-selector {
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
  }

  .stats-cards {
    margin-bottom: 20px;

    .stat-card {
      cursor: default;
      transition: transform 0.2s;

      &:hover {
        transform: translateY(-4px);
      }

      :deep(.el-card__body) {
        display: flex;
        align-items: center;
        padding: 20px;
      }

      .stat-icon {
        margin-right: 20px;
        opacity: 0.8;
      }

      .stat-content {
        flex: 1;

        .stat-value {
          font-size: 28px;
          font-weight: bold;
          margin-bottom: 8px;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }

      &.orders {
        .stat-icon {
          color: #409eff;
        }
        .stat-value {
          color: #409eff;
        }
      }

      &.sales {
        .stat-icon {
          color: #67c23a;
        }
        .stat-value {
          color: #67c23a;
        }
      }

      &.refunds {
        .stat-icon {
          color: #f56c6c;
        }
        .stat-value {
          color: #f56c6c;
        }
      }

      &.net-sales {
        .stat-icon {
          color: #e6a23c;
        }
        .stat-value {
          color: #e6a23c;
        }
      }
    }
  }

  .trend-card {
    .card-header {
      font-size: 16px;
      font-weight: bold;
    }
  }
}
</style>
